import { stringUtils } from 'my-ts-core';
import { AuthenticationService } from 'my-web-core/auth';
import { RouteMapManager } from 'my-ts-core/security'
import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import MainView from '@/MainView';
import RouteMapConfig from '@/shared/auth/route-map-config';
import Hook from '@/shared/redux/hook';

// import 'antd/dist/reset.css';
import '@/App.css';

function App() {
  const location = useLocation();
  const navigate = useNavigate();
  const currentUser = Hook.useAppSelector((state) => state.authentication.currentUser);
  const isAuthenticated = Hook.useAppSelector((state) => state.authentication.isAuthenticated);

  useEffect(() => {
    // When navigating from login to next view the url is not the target url but remains as login route.
    // That makes redirecting not work as expected.
    // That's why we are checking the authentication status and url.
    const url =
      AuthenticationService.isAuthenticated && stringUtils.isNotEmptyString(location.search)
        ? location.search
        : location.pathname;

    const search = AuthenticationService.isAuthenticated ? '' : location.search;
    
    // filter((a): a is string => !!a) acts like filter((a): a is string => a !== null && a !== undefined && a !== '')
    const roleAuthorities = currentUser?.fullRoles
      ?.map((r) => r.authority)
      .filter((a): a is string => !!a);

    if (url === '/') {
      // Makes home as default route.
      navigate('/home');
    } else if (AuthenticationService.isAuthenticated && url.toLocaleLowerCase().endsWith('login')) {
      // If user has logged in then no need to login page.
      navigate('/home');
    } else if (
      !RouteMapManager.checkCanActivateRoute(RouteMapConfig.getRequestMaps(), url, roleAuthorities) &&
      !isAuthenticated
    ) {
      // Redirects to login.
      navigate(`/authentication/login?redirectTo=${url + search}`, { replace: true });
    }
  }, [location.pathname, location.search, navigate, currentUser, isAuthenticated]);

  return <MainView />;
}

export default App;
